package ghost.gwtex.client;

import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.FocusListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * 支持 Double 校验 的文本框
 * 区分：显示格式(###.0##)和编辑格式(###.)
 * 右对齐
 * 
 * @author aibo 
 * @create date 2007-12-11 
 */

public class DoubleTextBox extends TextBox  implements FocusListener{
   private String viewFormat = "#,###.0##";
   private String editFormat = "####.###";
   public DoubleTextBox(){
	   super();
	   setTextAlignment(ALIGN_RIGHT);
   }
   
   public DoubleTextBox(double value){
	   this();
	   setDouble(value);
   }

   /**
	 * 按客户预设的格式显示。getLoginInfo().getNumberFormat()
	 * 
	 * @param value
	 */
	public void setDouble(double value) {
		NumberFormat nf = null;
		nf=NumberFormat.getFormat(viewFormat);
		setText(nf.format(value));
	}
	
	public double getDouble() {
		String str = getText();
		if (str == null || str.equals("")) {
			return 0;
		}		
		try {
			NumberFormat nf = null;
			nf = NumberFormat.getFormat(viewFormat);
			return nf.parse(getText());
		} catch (NumberFormatException nfe) {
			try {
				NumberFormat nf = null;
				nf = NumberFormat.getFormat(editFormat);
				return nf.parse(getText());
			} catch (NumberFormatException nfe2) {
				return 0;
			}
		}
	}
	
	public void onFocus(Widget sender) {
		double d = getDouble();
		NumberFormat nf = null;
		nf = NumberFormat.getFormat(editFormat);
		setText(nf.format(d));
		selectAll();
	}

	public void onLostFocus(Widget sender) {
		//焦点离开前，是 编辑的格式
			if (validate(editFormat)) {
				// 保留用户输入的，转为显示格式
				setDouble(getDouble());
			} else {
				//Window.alert("please input by pattern " + editFormat);
				setFocus(true);
			}		
	}

	/**
	 * 按指定的参数格式 去 校验
	 * 
	 * 增加校验：最大值
	 * 
	 * @param format
	 * @return
	 */
	private boolean validate(String format) {
		NumberFormat nf = NumberFormat.getFormat(format);
		try {
			nf.parse(getText());
		} catch (NumberFormatException nfe) {
			return false;
		}
		return true;
	}

	/**
	 * 按用户格式去 校验
	 * 
	 * @return
	 */
	private boolean validate() {
		return validate(viewFormat);
	}
	
	
	public String getViewFormat() {
		return viewFormat;
	}

	public void setViewFormat(String viewFormat) {
		this.viewFormat = viewFormat;
	}

	public String getEditFormat() {
		return editFormat;
	}

	public void setEditFormat(String editFormat) {
		this.editFormat = editFormat;
	}
}
